import time

from django.utils import timezone
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import status
from django.contrib.auth.hashers import check_password, make_password
from rest_framework.response import Response
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler


from user.models import User, Merchants, Application
from .settinse import UserSettin
from utils.pagnations import MyPagionation
# Create your views here.


# 注册
class RegisterAdd(APIView):
    def post(self, request):
        name = request.data.get('name')
        pwd = request.data.get('password')
        phone = request.data.get('phone')
        # merchan = request.data.get('merchan')
        if not all([name, pwd, phone]):
            return Response({'messages': 'The information is not complete. Please complete the information', 'code': status.HTTP_204_NO_CONTENT})
        user = User.objects.filter(username=name).count()
        if user > 0:
            return Response({'messages': 'The user already exists in', 'code': status.HTTP_204_NO_CONTENT})
        users = User.objects.create(username=name, password=make_password(pwd), mobile=phone, registration_time=time.strftime("%Y-%m-%d %H:%M:%S"))
        users.save()
        return Response({'messages': 'registered successfully', 'code': status.HTTP_201_CREATED})


# 登录
class LoginView(APIView):
    def post(self, request):
        name = request.data.get('name')
        print('用户名', name)
        pwd = request.data.get('password')
        try:
            user = User.objects.get(username=name)
        except Exception as e:
            return Response({'messages': 'The user does not exist. Please register first', 'code': status.HTTP_204_NO_CONTENT})
        user.login_time = time.strftime('%Y-%m-%d %H:%M:%S')
        if user.name != name:
            return Response({'messages': 'The user does not exist. Please register first', 'code': status.HTTP_402_PAYMENT_REQUIRED})

        print("密码：", user.password)
        rest = check_password( user.password, pwd)
        user.save()
        if rest:
            return Response({'messages': 'Incorrect password', 'code': status.HTTP_400_BAD_REQUEST})
        # if user.employees == True or user.rider == True:
        data = {'employees': user.employee,
                'rider': user.rider,}
        payliad = jwt_payload_handler(user)
        token = jwt_encode_handler(payliad)

        return Response({'messages': 'land successfully', 'token': token,'data': data, 'code': status.HTTP_200_OK})


# 创建商店
class Registration(APIView):
    def post(self, request):
        id = request.data.get('id')
        name = request.data.get('name')
        niname = request.data.get('nickname')
        store = request.data.get('store')
        usaan = Merchants.objects.filter(nickname=niname).first()
        if usaan:
            return Response({'messages': 'You have already applied. Please be patient', 'code': status.HTTP_204_NO_CONTENT})

        merchant = Merchants.objects.create(name=name, nickname=niname, store=store, registr_time=time.strftime('%Y-%m-%d %H:%M:%S'))
        merchant.save()
        merchants = Merchants.objects.filter(nickname=niname).all()
        mid = merchants[len(merchants)-1]
        User.objects.filter(id=id).update(merchan=mid).save()
        return Response({'messages': 'Store added successfully', 'code': status.HTTP_200_OK})


# 商家的申请
class Tarred(APIView):
    def post(self, request):
        id = request.data.get('id')
        merse = Application.objects.filter(moadfs=id, stutsa=1).first()
        if merse:
            merse.career = 1
            merse.save()
            modna = Merchants.objects.filter(store_sete=1).all()
            if modna:
                modna.store_sete = 4
                modna.save()
            return Response({'messages': 'Store application successful', 'code': status.HTTP_200_OK})
        else:
            return Response({'messages': 'Apply for failure', 'code': status.HTTP_500_INTERNAL_SERVER_ERROR})


# 员工添加
class Employs(APIView):
    def post(self, request):
        account = request.data.get('account')
        name = request.data.get('name')
        gender = request.data.get('gender')
        mobile = request.data.get('mobile')
        employees = request.data.get('employees')
        card = request.data.get('card')
        id = request.data.get('id')
        if not all([account, name, gender, card, mobile]):
            return Response({'messages': 'Please complete the information.', 'code': status.HTTP_401_UNAUTHORIZED})
        users = User.objects.all(name=name)
        if len(users.name) > 12:
            return Response({'messages': 'The name should be no more than 12 characters', 'code': status.HTTP_402_PAYMENT_REQUIRED})
        if users.mobile and users.card > 1:
            return Response({'messages': 'Mobile phone number and ID card are the only ones that cannot be repeated', 'code': status.HTTP_401_UNAUTHORIZED})
        if len(users.mobile) > 11:
            return Response({'messages': 'The phone number is too long. Please re-enter it', 'code': status.HTTP_402_PAYMENT_REQUIRED})
        if len(users.card) > 18:
            return Response({'messages': 'The ID card is too long, please re-enter it', 'code': status.HTTP_402_PAYMENT_REQUIRED})
        user = User.objects.create(account=account, name=name, card=card, merchan=id, registration_time=time.strftime("%Y-%m-%d %H:%M:%S"), password=make_password(123456789)).first()
        user.save()
        if user.employees != False:
            user.save()
        return Response({'messages': 'Adding an employee successfully', 'code': status.HTTP_200_OK})


# 员工的展示
class EmployeesShow(APIView):
    def get(self, request):
        # user = User.objects.filter(id=id)
        # if user.employees == False:
        #     return Response({'messages': 'No information on the employee was found', 'code': status.HTTP_401_UNAUTHORIZED})
        users = User.objects.filter(memployees=True).order_by('registration_time').all()

        datas = UserSettin(users, many=True)
        pagination_class = MyPagionation
        return Response({'data': datas.data, 'pagination_class': pagination_class, 'code': status.HTTP_200_OK})


# 修改密码
class Modify(APIView):
    def post(self, request):
        uid = request.data.get('id')
        pwd = request.data.get('pwd')
        pwd1 = request.data.get('pwd1')
        pwd2 = request.data.get('pwd2')
        user = User.objects.get(id=uid).first()
        user_pwd = check_password(user.password, pwd)
        if user_pwd:
            return Response({'messages': 'The password is incorrect. Please re-enter it', 'code': status.HTTP_402_PAYMENT_REQUIRED})
        if pwd1 != pwd2:
            return Response({'messages': 'The passwords are different. Please re-enter them', 'code': status.HTTP_402_PAYMENT_REQUIRED})

        users = User.objects.create(password=make_password(pwd1))
        users.save()
        return Response({'messages': 'Password changed successfully', 'code': status.HTTP_200_OK})


# 退出登录
class Logout(APIView):
    permission_classes = (jwt_payload_handler,)
    authentication_classes = (jwt_encode_handler,)

    def post(self, request):
        # simply delete the token to force a login
        request.auth.delete()  # This will not work
        return Response(status=status.HTTP_200_OK)


# 搜索
class SearchUser(APIView):
    def get(self,request):
        print("ASDFASF",request)
        key_word = request.query_params.get('keyword')
        print("!!@#$%%$#",key_word)
        users = User.objects.filter(name=key_word)
        if users.employees != True:
            return Response({'messages': 'Is not the employee', 'code': status.HTTP_400_BAD_REQUEST})
        ser = UserSettin(users,many=True)
        # print("+_)(*^",ser.data)
        return Response({"lit": ser.data})



